/**
 * 课表状态管理模块
 */
import { parseICS, organizeCoursesByWeek } from '@/utils/icsParser.js'

const state = {
	// 所有课程数据
	allCourses: [],
	
	// 按周组织的课表数据
	weeklySchedule: {},
	
	// 当前显示的周
	currentWeekKey: '',
	
	// 是否已导入课表
	hasSchedule: false,
	
	// 导入时间
	importTime: null,
	
	// 课表设置
	settings: {
		showWeekend: true,
		timeFormat24h: true,
		showEmptySlots: false,
		compactMode: false
	}
}

const mutations = {
	// 设置课程数据
	SET_COURSES(state, courses) {
		state.allCourses = courses
		state.hasSchedule = courses.length > 0
	},
	
	// 设置周课表数据
	SET_WEEKLY_SCHEDULE(state, weeklySchedule) {
		state.weeklySchedule = weeklySchedule
	},
	
	// 设置当前周
	SET_CURRENT_WEEK(state, weekKey) {
		state.currentWeekKey = weekKey
	},
	
	// 设置导入时间
	SET_IMPORT_TIME(state, time) {
		state.importTime = time
	},
	
	// 清空课表数据
	CLEAR_SCHEDULE(state) {
		state.allCourses = []
		state.weeklySchedule = {}
		state.currentWeekKey = ''
		state.hasSchedule = false
		state.importTime = null
	},
	
	// 更新设置
	UPDATE_SETTINGS(state, settings) {
		state.settings = { ...state.settings, ...settings }
	}
}

const actions = {
	// 导入课表数据
	async importSchedule({ commit }, icsContent) {
		try {
			// 解析ICS文件
			const courses = parseICS(icsContent)
			
			if (courses.length === 0) {
				throw new Error('未找到有效的课程信息')
			}
			
			// 按周组织数据
			const weeklySchedule = organizeCoursesByWeek(courses)
			
			// 提交到状态
			commit('SET_COURSES', courses)
			commit('SET_WEEKLY_SCHEDULE', weeklySchedule)
			commit('SET_IMPORT_TIME', Date.now())
			
			// 设置当前周
			const weekKeys = Object.keys(weeklySchedule).sort()
			if (weekKeys.length > 0) {
				// 找到包含当前日期的周，如果没有则使用第一周
				const now = new Date()
				let targetWeek = weekKeys[0]
				
				for (const weekKey of weekKeys) {
					const week = weeklySchedule[weekKey]
					if (now >= week.weekStart && now <= week.weekEnd) {
						targetWeek = weekKey
						break
					}
				}
				
				commit('SET_CURRENT_WEEK', targetWeek)
			}
			
			// 保存到本地存储
			uni.setStorageSync('schedule_data', {
				courses: courses,
				weeklySchedule: weeklySchedule,
				currentWeekKey: state.currentWeekKey,
				importTime: state.importTime,
				settings: state.settings
			})
			
			return { success: true, courseCount: courses.length }
			
		} catch (error) {
			console.error('导入课表失败:', error)
			return { success: false, error: error.message }
		}
	},
	
	// 加载本地数据
	loadScheduleData({ commit }) {
		const scheduleData = uni.getStorageSync('schedule_data')
		if (scheduleData) {
			// 恢复Date对象
			const restoredCourses = restoreDateObjects(scheduleData.courses || [])
			const restoredWeeklySchedule = restoreWeeklyScheduleDateObjects(scheduleData.weeklySchedule || {})
			
			commit('SET_COURSES', restoredCourses)
			commit('SET_WEEKLY_SCHEDULE', restoredWeeklySchedule)
			commit('SET_CURRENT_WEEK', scheduleData.currentWeekKey || '')
			commit('SET_IMPORT_TIME', scheduleData.importTime || null)
			
			if (scheduleData.settings) {
				commit('UPDATE_SETTINGS', scheduleData.settings)
			}
		}
	},
	
	// 切换到指定周
	switchToWeek({ commit, state }, weekKey) {
		if (state.weeklySchedule[weekKey]) {
			commit('SET_CURRENT_WEEK', weekKey)
			
			// 更新本地存储
			const scheduleData = uni.getStorageSync('schedule_data') || {}
			scheduleData.currentWeekKey = weekKey
			uni.setStorageSync('schedule_data', scheduleData)
		}
	},
	
	// 切换到上一周
	switchToPreviousWeek({ commit, state }) {
		const weekKeys = Object.keys(state.weeklySchedule).sort()
		const currentIndex = weekKeys.indexOf(state.currentWeekKey)
		
		if (currentIndex > 0) {
			const previousWeek = weekKeys[currentIndex - 1]
			commit('SET_CURRENT_WEEK', previousWeek)
			
			// 更新本地存储
			const scheduleData = uni.getStorageSync('schedule_data') || {}
			scheduleData.currentWeekKey = previousWeek
			uni.setStorageSync('schedule_data', scheduleData)
		}
	},
	
	// 切换到下一周
	switchToNextWeek({ commit, state }) {
		const weekKeys = Object.keys(state.weeklySchedule).sort()
		const currentIndex = weekKeys.indexOf(state.currentWeekKey)
		
		if (currentIndex < weekKeys.length - 1) {
			const nextWeek = weekKeys[currentIndex + 1]
			commit('SET_CURRENT_WEEK', nextWeek)
			
			// 更新本地存储
			const scheduleData = uni.getStorageSync('schedule_data') || {}
			scheduleData.currentWeekKey = nextWeek
			uni.setStorageSync('schedule_data', scheduleData)
		}
	},
	
	// 清空课表数据
	clearSchedule({ commit }) {
		commit('CLEAR_SCHEDULE')
		uni.removeStorageSync('schedule_data')
	},
	
	// 更新设置
	updateSettings({ commit, state }, newSettings) {
		commit('UPDATE_SETTINGS', newSettings)
		
		// 更新本地存储
		const scheduleData = uni.getStorageSync('schedule_data') || {}
		scheduleData.settings = state.settings
		uni.setStorageSync('schedule_data', scheduleData)
	}
}

const getters = {
	// 获取当前周的课程数据
	currentWeekCourses: (state) => {
		if (!state.currentWeekKey || !state.weeklySchedule[state.currentWeekKey]) {
			return {}
		}
		return state.weeklySchedule[state.currentWeekKey].courses
	},
	
	// 获取当前周信息
	currentWeekInfo: (state) => {
		if (!state.currentWeekKey || !state.weeklySchedule[state.currentWeekKey]) {
			return null
		}
		
		const week = state.weeklySchedule[state.currentWeekKey]
		const match = state.currentWeekKey.match(/W(\d+)/)
		const weekNumber = match ? parseInt(match[1]) : 1
		
		return {
			weekKey: state.currentWeekKey,
			weekNumber: weekNumber,
			weekStart: week.weekStart,
			weekEnd: week.weekEnd
		}
	},
	
	// 获取所有周的列表
	allWeeks: (state) => {
		return Object.keys(state.weeklySchedule)
			.sort()
			.map(weekKey => {
				const week = state.weeklySchedule[weekKey]
				const match = weekKey.match(/W(\d+)/)
				const weekNumber = match ? parseInt(match[1]) : 1
				
				return {
					weekKey,
					weekNumber,
					weekStart: week.weekStart,
					weekEnd: week.weekEnd
				}
			})
	},
	
	// 获取某天的课程
	getDayCourses: (state, getters) => (weekday) => {
		const currentWeekCourses = getters.currentWeekCourses
		return currentWeekCourses[weekday] || []
	},
	
	// 获取今天的课程
	todayCourses: (state, getters) => {
		const today = new Date()
		const weekday = today.getDay() // 0=周日, 1=周一...
		return getters.getDayCourses(weekday)
	},
	
	// 获取课表统计信息
	scheduleStats: (state) => {
		const stats = {
			totalCourses: state.allCourses.length,
			totalWeeks: Object.keys(state.weeklySchedule).length,
			subjects: new Set(),
			teachers: new Set(),
			locations: new Set()
		}
		
		state.allCourses.forEach(course => {
			if (course.title) stats.subjects.add(course.title)
			if (course.teacher) stats.teachers.add(course.teacher)
			if (course.location) stats.locations.add(course.location)
		})
		
		return {
			...stats,
			subjectCount: stats.subjects.size,
			teacherCount: stats.teachers.size,
			locationCount: stats.locations.size
		}
	}
}

/**
 * 恢复课程数组中的Date对象
 * @param {Array} courses - 课程数组
 * @returns {Array} 恢复Date对象后的课程数组
 */
function restoreDateObjects(courses) {
	return courses.map(course => ({
		...course,
		startTime: course.startTime ? new Date(course.startTime) : null,
		endTime: course.endTime ? new Date(course.endTime) : null
	}))
}

/**
 * 恢复周课表数据中的Date对象
 * @param {Object} weeklySchedule - 周课表数据
 * @returns {Object} 恢复Date对象后的周课表数据
 */
function restoreWeeklyScheduleDateObjects(weeklySchedule) {
	const restored = {}
	
	Object.keys(weeklySchedule).forEach(weekKey => {
		const week = weeklySchedule[weekKey]
		restored[weekKey] = {
			weekStart: week.weekStart ? new Date(week.weekStart) : null,
			weekEnd: week.weekEnd ? new Date(week.weekEnd) : null,
			courses: {}
		}
		
		// 恢复每天课程中的Date对象
		Object.keys(week.courses || {}).forEach(dayKey => {
			restored[weekKey].courses[dayKey] = restoreDateObjects(week.courses[dayKey] || [])
		})
	})
	
	return restored
}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters
} 